package com.mos.iot.mqtt.listener.converter.impl;

import com.mos.iot.mqtt.listener.converter.MessageConverter;
import com.mos.iot.mqtt.util.JsonUtil;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MqttJsonMessageConverter implements MessageConverter {

    @Override
    public <T> T convert(Object value, Class<T> target, T defaultValue) throws IllegalArgumentException {
        if(value != null) {
            if (value instanceof MqttMessage) {
                MqttMessage message = (MqttMessage) value;
                String content = new String(message.getPayload());
                return JsonUtil.parseObject(content, target);
            } else if (value instanceof String) {
                return JsonUtil.parseObject((String) value, target);
            } else if(target.equals(String.class)) {
                return (T) JsonUtil.toJSONString(value);
            }
        }
        return defaultValue;
    }
}
